package com.wlstock.funi.runnable;

import android.os.Handler;

import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.dao.PositionDao;
import com.wlstock.funi.dao.SelfFundSetDao;
import com.wlstock.funi.model.OperateModel;
import com.wlstock.funi.model.SelfFundSetModel;
import com.wlstock.funi.utils.CaculateUtils;
import com.wlstock.funi.utils.HttpUtils;
import com.wlstock.funi.utils.IOUtils;
import com.wlstock.funi.utils.LogUtils;
import com.wlstock.funi.utils.NotiIdGenerator;
import com.wlstock.funi.utils.NotiUtils;
import com.wlstock.funi.utils.StockUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

public class OrderBuy {

	private static final long DEFAULT_SECONDS = 30;
	private String stkcode;
	private float price;
	private long qty;
	private OperateModel buyModel;
	private String stkName;
	private OrderListener listener;
	private int maxTime = 4;

	public OrderBuy(String stkcode,String stkName, float price, long qty) {
		super();
		this.stkcode = stkcode;
		this.price = price;
		this.qty = qty;
		this.stkName = stkName;
	}
	
	public OrderBuy(OperateModel model,String stkcode,String stkName ,float price, long qty){
		this(stkcode,stkName,price,qty);
		this.buyModel = model;
	}

	public void buy(OrderListener oListener){

		if (!StockUtils.isStkValid(stkcode) && price<=0 && qty<100){
			NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.generate(stkcode, NotiIdGenerator.GenerFrom.REALTRADE),stkName+ "买入下单失败", "基本信息出错,请检查程序", 0);
			return;
		}
		this.listener = oListener;
		FundAsyTask<Void, Void, Object> fundAsyTask = new FundAsyTask<>();
		fundAsyTask.backListener = new FundAsyTask.TaskLitener<Void, Object>() {
			@Override
			public Object doInBackground(Void... param) {
				HttpClient client = new DefaultHttpClient();
				try {
					// Request
					// URL:https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=submitOrder
					HttpPost buyPost = new HttpPost("https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=submitOrder");
					HashMap<String, String> parmHash = new HashMap<String, String>();
					// market:1 market:2
					// secuid:A303112208 secuid:0186265187
					// stkcode:600658 (601 603)开头 stkcode:002021(300,000)
					// price:11.16
					// qty:100
					// bsflag:1
					// bsprop:0
					// type:stock

					parmHash.put("market", StockUtils.parseStkCode2Market(OrderBuy.this.stkcode));
					parmHash.put("secuid", StockUtils.parseStkCode2SecuId(OrderBuy.this.stkcode));
					parmHash.put("stkcode", OrderBuy.this.stkcode);
					parmHash.put("price", String.valueOf(price));
					parmHash.put("qty", String .valueOf(qty));
					parmHash.put("bsflag", "1");
					parmHash.put("bsprop", "0");
					parmHash.put("type", "stock");

					List<? extends NameValuePair> params = HttpUtils.getParms(parmHash );
					// Accept:application/json, text/javascript, */*
					// Accept-Encoding:gzip, deflate
					// Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
					// Connection:keep-alive
					// Content-Length:90
					// Content-Type:application/x-www-form-urlencoded
					// Cookie:JSESSIONID=Qk0HWprRL3fNvzrBxrP2hFZD0MmbtwQg4S9Qf1Fncm02QNykd5Lh!-908755652!297676372;
					// ssl=etrade-ssl-1
					// Host:etrade.cs.ecitic.com
					// Origin:https://etrade.cs.ecitic.com
					// Referer:https://etrade.cs.ecitic.com/ymtrade/stock/buy.jsp
					// User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
					// X-Requested-With:XMLHttpRequest
					HttpEntity entity = new UrlEncodedFormEntity(params);
					buyPost.setEntity(entity);
					buyPost.addHeader("Accept", "application/json, text/javascript, */*");
					buyPost.addHeader("Accept-Encoding","gzip, deflate");
					buyPost.addHeader("Accept-Language","zh-CN,zh;q=0.8,en;q=0.6");
					buyPost.addHeader("Connection","keep-alive");
					buyPost.addHeader("Content-Type","application/x-www-form-urlencoded");
					buyPost.addHeader("Cookie",FundApplication.cookie);
					buyPost.addHeader("Referer","https://etrade.cs.ecitic.com/ymtrade/stock/buy.jsp");
					buyPost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");
					buyPost.addHeader("X-Requested-With","XMLHttpRequest");

					HttpResponse buyPostResponse = client.execute(buyPost);

					if (buyPostResponse.getStatusLine().getStatusCode() == 200) {
						String result = IOUtils.is2Str(buyPostResponse.getEntity().getContent());
						return result;
					}
					//除了上面这种情况以外都是错误
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					client.getConnectionManager().shutdown();
				}

				return null;
			}
		};

		fundAsyTask.resultListener = new FundAsyTask.TaskResultListener<Object>() {
			@Override
			public void onPostResult(Object o) {
				if (o!=null){
					String result = (String)o;
					try {
						JSONObject obj = new JSONObject(result);
						if (obj.getString("cssweb_type").equals("success")) {
							LogUtils.i("买入下单成功"+result);
							if (buyModel!=null) {
								NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.generate(stkcode, NotiIdGenerator.GenerFrom.REALTRADE),stkName+ "买入下单成功"+" 价格:"+price+" 数量:"+qty +"排名:"+buyModel.range+" 本期:"+ CaculateUtils.getPercentByFloat(buyModel.getProfitRate()), obj.getString("cssweb_msg") +"\n"+"¥", 0);
							}else{
								NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.generate(stkcode, NotiIdGenerator.GenerFrom.REALTRADE),stkName+ "买入下单成功"+" 价格:"+price+" 数量:"+qty, obj.getString("cssweb_msg"), 0);
							}
							//将设置中的卖出选项监听清除掉
							SelfFundSetDao.getInstance(FundApplication.getInstance()).updatePendState(stkcode, SelfFundSetModel.DONE, OperateModel.TradeType_BUY);
							//更新仓位信息
							PositionDao.getInstance(FundApplication.getInstance()).updateCurPosition(OperateModel.TradeType_BUY, qty, Float.valueOf(price));

							if (listener!=null){
								listener.orderSuccess(OperateModel.TradeType_BUY,stkcode,stkName,price,qty);
							}
						} else {
							NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.generate(stkcode, NotiIdGenerator.GenerFrom.REALTRADE),stkName+ "买入下单失败:30秒后重新下单", result, 0);
							repeatAfterSeconds(DEFAULT_SECONDS);
							if (listener!=null){
								listener.orderFaile(OperateModel.TradeType_BUY,stkcode,stkName,price,qty,result);
							}
						}
						FundApplication.getInstance().playSoundPool(NotiIdGenerator.GenerFrom.REALTRADE);
					}catch (JSONException e){
						e.printStackTrace();
					}
				}else {
					orderFaile();
					if (listener!=null){
						listener.orderFaile(OperateModel.TradeType_BUY,stkcode,stkName,price,qty,"接口访问失败");
					}
				}
			}
		};

		fundAsyTask.execute();
	}

	private void repeatAfterSeconds(long seconds) {
		maxTime --;
		if (maxTime<=0)
			return;
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				buy(listener);
			}
		},seconds*1000);
	}


	private void orderFaile() {
		NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.generate(stkcode, NotiIdGenerator.GenerFrom.REALTRADE),stkName+ "买入下单失败", "接口访问失败", 0);
		FundApplication.getInstance().playSoundPool(NotiIdGenerator.GenerFrom.REALTRADE);
	}



	
}
